<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
        placeholder="请输入搜索关键词"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>

    <!-- 联想建议 -->
    <search-suggesion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggesion>

    <!-- 历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
import SearchSuggesion from './components/search-suggestion'
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
import { getSearchHistories } from '@/api/search'
import { mapState } from 'vuex'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('search-histories') || [] // 搜索历史数据记录
    }
  },
  components: {
    SearchSuggesion,
    SearchHistory,
    SearchResult
  },
  computed: {
    ...mapState(['user'])
  },
  created () {
    this.loadSearchHistories()
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      const index = this.searchHistories.indexOf(this.searchText)
      if (index !== -1) {
        // 把重复项删除
        this.searchHistories.splice(index, 1)
      }
      // 记录搜索历史记录
      this.searchHistories.unshift(this.searchText)

      // 如果用户已登录，则把搜索历史记录存储到线上

      // 如果没有登录页，则把搜索历史记录存储到本地
      setItem('search-histories', this.searchHistories)

      // 展示搜索结果
      this.isResultShow = true
    },
    async loadSearchHistories () {
      // 因为后端帮我们存储的用户搜索历史记录太少了（只有四条）
      // 所以我们这里让后端返回的历史记录和本地的历史记录合并到一起

      let seachHistories = getItem('search-histories') || []
      if (this.user) {
        const { data } = await getSearchHistories()
        // 合并数组： [...数组，...数组]
        // 把set转为数组： [...Set对象]
        // 数组去重： [...new Set(...数组, ...数组)]
        seachHistories = [
          ...new Set([...seachHistories, ...data.data.keywords])
        ]
      }
      this.searchHistories = seachHistories
    }
  }
}
</script>

<style>
</style>
